package com.hbsoft.wechat.controller;

import com.hb.annotation.LoginNotRequired;
import com.hb.bean.CallResult;
import com.hb.controller.ABaseController;
import com.hb.util.BasePassUtil;
import com.hb.util.ExcelUtil;
import com.hbsoft.common.constant.Constant;
import com.hbsoft.config.SysConfigInfo;
import com.hbsoft.util.*;
import com.hbsoft.wechat.bean.*;
import com.hbsoft.wechat.dao.WXUserDao;
import com.hbsoft.wechat.dao.WXUserLoginInfoDao;
import com.hbsoft.wechat.dao.service.*;
import com.hbsoft.wechat.service.GetBattleService;
import com.hbsoft.wechat.service.SwanService;
import com.hbsoft.wechat.service.WechatAppletService;
import com.hbsoft.wechat.vo.DeptVo;
import com.hbsoft.wechat.vo.ExportInfoVo;
import com.hbsoft.wechat.vo.UserVo;
import com.hbsoft.wechat.vo.WxField;
import net.iharder.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
import java.util.*;

@RestController
@RequestMapping(value = "", produces = "application/json;charset=UTF-8")
public class WechatAppletController extends ABaseController{

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private WechatUtil wechatUtil;

	@Autowired
	private WXUserDaoService wxUserDaoService;

	@Autowired
	private WXUserLoginInfoDaoService wxUserLoginInfoDaoService;

	@Autowired
	private GetBattleService getBattleService;

	@Autowired
	private WXUserDao wxUserDao;

	@Autowired
	private WXUserLoginInfoDao wxUserLoginInfoDao;

	@Autowired
	private DeptYQDaoService deptYQDaoService;

	@Autowired
	private SwanDaoService swanDaoService;

	@Autowired
	private SwanLogDaoService swanLogDaoService;

	@Autowired
	private SwanService swanService;

	@Autowired
	private WechatAppletService wechatAppletService;

	@Autowired
	private BusInfoDaoService busInfoDaoService;

	@Autowired
	private ImageUtil imageUtil;


	
	@LoginNotRequired
	@PostMapping(value = "wechatAppletLogin")
	@ResponseBody
	public String wechatAppletLogin(String code){
		CallResult<Map<String,Object>> result = new CallResult<Map<String,Object>>();
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			if(StringUtils.isBlank(code)){
				result.setCode(400);
				result.setMessage("参数有误");
				return gson1.toJson(result);
			}
			Map<String,Object> wxMap = wechatUtil.getWXAppOpenidAndSessionKeyByCode(code);
			String openid = (String) wxMap.get("openid");
			if(isEmpty(openid)){
				logger.info("未获取到openid，重新获取");
				wxMap = wechatUtil.getWXAppOpenidAndSessionKeyByCode(code);
				openid = (String) wxMap.get("openid");
			}
			if(wxMap != null && !isEmpty(openid)){
				String sessionId = session.getId();
				String sessionKey = (String) wxMap.get("session_key");
				session.setAttribute("wxAppOpenid",openid);
				session.setAttribute("session_key",sessionKey);
				map.put("sessionId", sessionId);
				map.put("openid", openid);
				map.put("session_key",sessionKey);
				WXUser param = new WXUser();
				param.setOpenid(openid);
				WXUser wxUser = wxUserDaoService.getByField(param);
				if(wxUser != null){
					session.setAttribute("wxUser",wxUser);
					UserVo vo = new UserVo();
					BeanUtils.copyProperties(wxUser,vo);
					//vo.setPhone(StringUtil.hidePhone(vo.getPhone()));
					map.put("wxUser",vo);
				}
                result.setData(map);
                result.setCode(0);
                result.setMessage("操作成功");

				WXUserLoginInfo record = new WXUserLoginInfo();
				record.setOpenid(openid);
				record.setCreateOn(new Date());
				wxUserLoginInfoDaoService.add(record);


			}else{
				result.setCode(400);
				result.setMessage("未获取到openid");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(400);
			result.setMessage("操作失败");
		}
		return gson1.toJson(result);
	}


	@LoginNotRequired
	@PostMapping(value = "getWXAppphone")
	@ResponseBody
	public String getWXAppphone(String encryptedData, String iv, String session_key,HttpSession session) {
		logger.info("解密手机号入参 encryptedData：{},iv:{},session_key:{}",encryptedData,iv,session_key);
		if(isEmpty(session_key)){
			session_key = (String) session.getAttribute("session_key");
			logger.info("未获取到session_key,从session中获取:{}",session_key);
		}
		String str = "";
		try {
			byte[] encrypData = Base64.decode(encryptedData);
			byte[] ivData = Base64.decode(iv);
			byte[] sessionKey = Base64.decode(session_key);
			str = decrypt(sessionKey, ivData, encrypData);
			logger.info("解密后内容：{}",str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}


	public  String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
		AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
		cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
		//解析解密后的字符串  
		return new String(cipher.doFinal(encData), "UTF-8");
	}


	@LoginNotRequired
	@PostMapping(value = "wxAppRegister")
	@ResponseBody
	public String wxAppRegister(UserVo vo,HttpSession session){
		logger.info("注册入参：{}",vo.toString());
		CallResult<String> callResult = new CallResult<>();
		if(StringUtils.isBlank(vo.getPhone()) || vo.getPhone().length() != 11){
			callResult.setCode(400);
			callResult.setMsg("请输入手机号码");
			return GsonUtil.toJson(callResult);
		}
		if(StringUtils.isBlank(vo.getUserName())){
			callResult.setCode(400);
			callResult.setMsg("请输入姓名");
			return GsonUtil.toJson(callResult);
		}

		WXUser param = new WXUser();
		String openid = (String) session.getAttribute("wxAppOpenid");
		if(StringUtils.isBlank(openid)){
			callResult.setCode(400);
			callResult.setMsg("参数有误，请重新登录");
			return GsonUtil.toJson(callResult);
		}

		try {
			param.setOpenid(openid);
			WXUser wxUser = wxUserDaoService.getByField(param);
			if(wxUser == null){
				WXUser param1 = new WXUser();
				param1.setPhone(vo.getPhone());
				WXUser wxUserVolidate = wxUserDaoService.getByField(param1);
				if(wxUserVolidate != null){
					callResult.setCode(400);
					callResult.setMsg("手机号已存在");
					return GsonUtil.toJson(callResult);
				}

				wxUser = new WXUser();
				wxUser.setOpenid(openid);
				wxUser.setPhone(vo.getPhone());
				wxUser.setUserName(vo.getUserName());
				wxUser.setAddress(vo.getAddress());
				wxUser.setOrgCode(vo.getOrgCode());
				wxUser.setCreateOn(new Date());
				wxUser.setUpdateOn(new Date());
				wxUserDaoService.add(wxUser);
			}else{
				if("null".equals(vo.getUserName()) || "undefined".equals(vo.getUserName())){
					vo.setUserName(null);
				}
				if("null".equals(vo.getAddress()) || "undefined".equals(vo.getAddress())){
					vo.setAddress(null);
				}
				if("null".equals(vo.getJob()) || "undefined".equals(vo.getJob())){
					vo.setJob(null);
				}
				if("null".equals(vo.getIdCard()) || "undefined".equals(vo.getIdCard())){
					vo.setIdCard(null);
				}
				if("null".equals(vo.getTrainNum()) || "undefined".equals(vo.getTrainNum())){
					vo.setTrainNum(null);
				}
				BeanUtils.copyProperties(vo,wxUser);
				wxUser.setUpdateOn(new Date());
				logger.info("修改时信息：{}",wxUser.toString());
				wxUserDaoService.set(wxUser);
			}
			session.setAttribute("wxUser",wxUser);
			callResult.setCode(0);
			callResult.setMsg("操作成功");
		} catch (Exception e) {
			e.printStackTrace();
			callResult.setCode(400);
			callResult.setMsg("操作失败");
		}

		return GsonUtil.toJson(callResult);
	}


	@LoginNotRequired
	@RequestMapping(value = "getBattleInfo")
	@ResponseBody
	public String getBattleInfo(){
		BattleInfo battleInfo = getBattleService.getBattleInfo();
		return GsonUtil.toJson(battleInfo);
	}

	@LoginNotRequired
	@RequestMapping(value = "getWxAappQrCode")
	@ResponseBody
	public String getWxAappQrCode(String qrParam){
		String qrCodeFileName = wechatUtil.getWxAappQrCode(qrParam);
		return qrCodeFileName;
	}

	@LoginNotRequired
	@RequestMapping(value = "getOrgLogo")
	@ResponseBody
	public String getOrgLogo(String qrParam){

		return "https://web.vfpbs.cn/battle/img/hlwlogo.png";
	}

	@LoginNotRequired
	@RequestMapping(value = "getWxUser")
	@ResponseBody
	public String getWxUser(String openid){
		CallResult<UserVo> callResult = new CallResult<>();
		WXUser wxUser = null;
		try {
			if(isEmpty(openid)){
				wxUser = (WXUser) session.getAttribute("wxUser");
			}else {
				WXUser param = new WXUser();
				param.setOpenid(openid);
				wxUser = wxUserDaoService.getByField(param);
			}
			UserVo vo = new UserVo();
			BeanUtils.copyProperties(wxUser,vo);
			callResult.setCode(0);
			callResult.setMsg("查询成功");
			callResult.setData(vo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return GsonUtil.toJson(callResult);
	}


	@LoginNotRequired
	@RequestMapping(value = "getWxUserTotal")
	@ResponseBody
	public String getWxUserTotal(){
		CallResult<Map<String,String>> callResult = new CallResult<>();
		try {
			int registerNum = wxUserDao.findPagingCount(null);
			Map<String,String> map = new HashMap<>();
			if(registerNum > 0){
				map.put("registerNum",registerNum+"");
			}
			callResult.setData(map);
			callResult.setCode(0);
			callResult.setMsg("查询成功");
		} catch (Exception e) {
			e.printStackTrace();
			callResult.setCode(400);
			callResult.setMsg("查询失败");
		}
		return GsonUtil.toJson(callResult);
	}

	@LoginNotRequired
	@RequestMapping(value = "getWxUserLogTotal")
	@ResponseBody
	public String getWxUserLogTotal(){
		CallResult<Map<String,String>> callResult = new CallResult<>();
		try {
			int wxUserLoginNum = wxUserLoginInfoDao.findPagingCount(null);
			Map<String,String> map = new HashMap<>();
			if(wxUserLoginNum > 0){
				map.put("wxUserLoginNum",wxUserLoginNum+"");
			}
			callResult.setData(map);
			callResult.setCode(0);
			callResult.setMsg("查询成功");
		} catch (Exception e) {
			e.printStackTrace();
			callResult.setCode(400);
			callResult.setMsg("查询失败");
		}
		return GsonUtil.toJson(callResult);
	}


    @LoginNotRequired
    @RequestMapping(value = "getDeptClockInInfo")
    @ResponseBody
    public String getDeptClockInInfo(ImportUserClockInInfo importUserClockInInfo) {
        Map<String, Object> map = new HashMap<String, Object>();
		if(hb_user == null){
			map.put("code", 400);
			map.put("msg", "请重新登录");
			return GsonUtil.toJson(map);
		}
		try {
			if(!"1".equals(importUserClockInInfo.getFlag())){
				if(isEmpty(importUserClockInInfo.getDeptId())){
					DeptYQ param = new DeptYQ();
					param.setMobile(hb_user.getName());
					List<DeptYQ> deptlist = deptYQDaoService.getAll(param);
					if(deptlist != null && deptlist.size() > 0){
						importUserClockInInfo.setDeptId(String.valueOf(deptlist.get(0).getId_prikey()));

					}else{
						map.put("code", 0);
						map.put("msg", "无数据");
						return GsonUtil.toJson(map);
					}
				}
			}

			Integer count = wxUserDao.findClockInInfoPagingCount(importUserClockInInfo);
			List<ImportUserClockInInfo> list = wxUserDao.findClockInInfoPagingData(importUserClockInInfo);
			map.put("code", 0);
			map.put("msg", "获取成功");
			map.put("count", count);
			map.put("data", list);

		} catch (Exception e) {
			e.printStackTrace();
		}

        return GsonUtil.toJson(map);
    }

	@LoginNotRequired
	@RequestMapping(value = "getDeptInfo")
	@ResponseBody
	public String getDeptInfo(String flag) {
		logger.info("user_id_prikey:{}",user_id_prikey);
		logger.info("userId:{}",userId);
		logger.info("user:{}",GsonUtil.toJson(user));
		logger.info("hb_user:{}",GsonUtil.toJson(hb_user));
		CallResult<List<DeptVo>> result = new CallResult<>();
		List<DeptVo> voList = new ArrayList<>();
		try {
			DeptYQ param = new DeptYQ();
			param.setMobile(hb_user.getName());
			List<DeptYQ> list = deptYQDaoService.getAll(param);
			for(DeptYQ dy: list){
				DeptVo vo = new DeptVo();
				vo.setDeptId(dy.getId_prikey());
				vo.setDpetName(dy.getDpetName());
				voList.add(vo);
			}
			result.setCode(0);
			result.setMsg("操作成功");
			result.setData(voList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return GsonUtil.toJson(result);
	}

	@LoginNotRequired
	@RequestMapping(value = "getAllDeptInfo")
	@ResponseBody
	public String getDeptInfo() {
		logger.info("user_id_prikey:{}",user_id_prikey);
		logger.info("userId:{}",userId);
		logger.info("user:{}",GsonUtil.toJson(user));
		logger.info("hb_user:{}",GsonUtil.toJson(hb_user));
		CallResult<List<DeptVo>> result = new CallResult<>();
		List<DeptVo> voList = new ArrayList<>();
		try {
			List<DeptYQ> list = deptYQDaoService.getAll(null);
			for(DeptYQ dy: list){
				DeptVo vo = new DeptVo();
				vo.setDeptId(dy.getId_prikey());
				vo.setDpetName(dy.getDpetName());
				voList.add(vo);
			}
			result.setCode(0);
			result.setMsg("操作成功");
			result.setData(voList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return GsonUtil.toJson(result);
	}



	@LoginNotRequired
    @RequestMapping(value = "exportDeptClockinfo")
    @ResponseBody
    public String exportDeptClockinfo(HttpServletResponse response,ImportUserClockInInfo importUserClockInInfo){
        CallResult<String> result = new CallResult<String>();
		if(hb_user == null){
			result.setCode(400);
			result.setMsg("请重新登录");
			return  GsonUtil.toJson(response);
		}
        List<String> titleList = new ArrayList<>();
        titleList.add("单位名称");
        titleList.add("姓名");
        titleList.add("手机号码");
        titleList.add("体温");
        titleList.add("是否正常");
        titleList.add("登记时间");

        List<String> columnList = new ArrayList<>();
        columnList.add("dpetName");
        columnList.add("name");
        columnList.add("mobile");
        columnList.add("temperature");
        columnList.add("normal");
        columnList.add("createDateTime");

        List<Map<String,Object>> list = null;
        try {
			if(!"1".equals(importUserClockInInfo.getFlag())) {
				if (isEmpty(importUserClockInInfo.getDeptId())) {
					DeptYQ param = new DeptYQ();
					param.setMobile(hb_user.getName());
					List<DeptYQ> deptlist = deptYQDaoService.getAll(param);
					if (deptlist != null && deptlist.size() > 0) {
						importUserClockInInfo.setDeptId(String.valueOf(deptlist.get(0).getId_prikey()));
					} else {
						ExcelUtil.exportExcelBigData(response,"员工打卡信息.xlsx",titleList,columnList,list);
						return null;
					}
				}
			}
			list = wxUserDao.findClockInInfoMapData(importUserClockInInfo);
			ExcelUtil.exportExcelBigData(response,"员工打卡信息.xlsx",titleList,columnList,list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setCode(0);
        result.setMessage("导出成功");
        return  GsonUtil.toJson(result);
    }


	@LoginNotRequired
	@RequestMapping(value = "getExportInfo")
	@ResponseBody
	public String getDeptByIdPrikey(String id_prikey){
		CallResult<ExportInfoVo> callResult = new CallResult<>();
		if(isEmpty(id_prikey)){
			callResult.setCode(400);
			callResult.setMsg("参数有误");
			return GsonUtil.toJson(callResult);
		}
		try {
			DeptYQ deptYQ = deptYQDaoService.getById(Integer.valueOf(id_prikey));
			ExportInfoVo vo = new ExportInfoVo();
			if(deptYQ!= null){
				vo.setUserName(deptYQ.getMobile());
				Map paramMap = new HashMap();
				paramMap.put("name",vo.getUserName());
				Map map = wxUserDao.findHBUserByName(paramMap);
				if(map != null){
				    String name = ((String)map.get("name")).trim();
				    String password = ((String)map.get("password")).trim();
					String pass = BasePassUtil.transformationPlaintext(name,password);
					vo.setPassword(pass);
				}
			}
			vo.setExportUrl("http://web.vfpbs.cn");
			callResult.setCode(0);
			callResult.setMsg("操作成功");
			callResult.setData(vo);
		} catch (Exception e) {
			callResult.setCode(400);
			callResult.setMsg("操作失败");
		}

		return GsonUtil.toJson(callResult);
	}

	@LoginNotRequired
	@RequestMapping(value = "getExportSwanInfo")
	@ResponseBody
	public String getExportSwanInfo(String id_prikey){
		CallResult<ExportInfoVo> callResult = new CallResult<>();
		if(isEmpty(id_prikey)){
			callResult.setCode(400);
			callResult.setMsg("参数有误");
			return GsonUtil.toJson(callResult);
		}
		try {
			Swan swan = swanDaoService.getById(Integer.valueOf(id_prikey));
			String phone = "";
			ExportInfoVo vo = new ExportInfoVo();
			if(swan != null){
				WXUser param = new WXUser();
				param.setOpenid(swan.getOpenId());
				List<WXUser> wxUsers = wxUserDaoService.getAll(param);

				if(wxUsers != null && wxUsers.size()>0){
					vo.setUserName(wxUsers.get(0).getPhone());
					Map paramMap = new HashMap();
					paramMap.put("name",vo.getUserName());
					Map map = wxUserDao.findHBUserByName(paramMap);
					if(map != null){
                        String name = ((String)map.get("name")).trim();
                        String password = ((String)map.get("password")).trim();
                        String pass = BasePassUtil.transformationPlaintext(name,password);
						vo.setPassword(pass);
					}
				}
			}

			vo.setExportUrl("http://web.vfpbs.cn");
			callResult.setCode(0);
			callResult.setMsg("操作成功");
			callResult.setData(vo);
		} catch (Exception e) {
			callResult.setCode(400);
			callResult.setMsg("操作失败");
		}

		return GsonUtil.toJson(callResult);
	}




	@LoginNotRequired
	@RequestMapping(value = "getSwanInfo")
	@ResponseBody
	public String getSwanInfo(String flag) {
		CallResult<List<DeptVo>> result = new CallResult<>();
		if(hb_user == null){
			result.setCode(400);
			result.setMsg("请重新登录");
			return  GsonUtil.toJson(result);
		}
		try {
			WXUser wxUser = new WXUser();
			wxUser.setPhone(hb_user.getName());
			List<WXUser> wxUsers = wxUserDao.findAll(wxUser);
			if(wxUsers != null && wxUsers.size() > 0){
				Swan swan = new Swan();
				swan.setOpenId(wxUsers.get(0).getOpenid());
				List<Swan> swans = swanDaoService.getAll(swan);
				List<DeptVo> voList = new ArrayList<>();
				if(swans != null){
					for(Swan sw : swans){
						DeptVo vo = new DeptVo();
						vo.setDeptId(sw.getId_prikey());
						vo.setDpetName(sw.getName());
						voList.add(vo);
					}
					result.setData(voList);
					result.setCode(0);
					result.setMsg("查询成功");

				}
			}else{
				result.setCode(400);
				result.setMsg("未查询到部门信息");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return  GsonUtil.toJson(result);
	}


	@LoginNotRequired
	@RequestMapping(value = "getLatestDeptInfo")
	@ResponseBody
	public String getLatestDeptInfo(String openId) {
		CallResult<DeptVo> result = new CallResult<>();
		try {
			if(isEmpty(openId)){
				result.setCode(400);
				result.setMsg("参数有误");
				return  GsonUtil.toJson(result);
			}
			WXUser userParam = new WXUser();
			userParam.setOpenid(openId);
			List<WXUser> wxUsersList = wxUserDaoService.getAll(userParam);
			if(wxUsersList != null && wxUsersList.size() > 0){
				DeptYQ deptParam = new DeptYQ();
				deptParam.setMobile(wxUsersList.get(0).getPhone());
				List<DeptYQ> deptlist = deptYQDaoService.getAll(deptParam);
				if(deptlist != null && deptlist.size() > 0){
					DeptYQ deptYQ = deptlist.get(0);
					DeptVo vo = new DeptVo();
					vo.setDpetName(deptYQ.getDpetName());
					vo.setLogoUrl(deptYQ.getIcon());
					result.setCode(0);
					result.setMsg("查询成功");
					result.setData(vo);
					return  GsonUtil.toJson(result);
				}
			}else {
				result.setCode(400);
				result.setMsg("参数有误");
				return  GsonUtil.toJson(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return  GsonUtil.toJson(result);
	}


	@LoginNotRequired
	@RequestMapping(value = "getWsanClockInInfo")
	@ResponseBody
	public String getWsanClockInInfo(SwanLog log) {
		CallResult<List<DeptVo>> result = new CallResult<>();
		if(hb_user == null){
			result.setCode(400);
			result.setMsg("请重新登录");
			return  GsonUtil.toJson(result);
		}
		Map map = new HashMap();
		try {
			if(log.getSwanId() == null) {
				WXUser wxUser = new WXUser();
				wxUser.setPhone(hb_user.getName());
				List<WXUser> wxUsers = wxUserDao.findAll(wxUser);
				if (wxUsers != null && wxUsers.size() > 0) {
					Swan swan = new Swan();
					swan.setOpenId(wxUsers.get(0).getOpenid());
					List<Swan> swans = swanDaoService.getAll(swan);
					if (swans != null) {
						log.setSwanId(swans.get(0).getId_prikey());
					}
				}else {
                    result.setCode(0);
                    result.setMsg("权限不足");
                    return GsonUtil.toJson(result);
                }
			}
			map = swanLogDaoService.getPagingData(log);



		}catch (Exception e){
			e.printStackTrace();
		}
		return GsonUtil.toJson(map);
	}


	@LoginNotRequired
	@RequestMapping(value = "exportSwanClockinfo")
	@ResponseBody
	public String exportSwanClockinfo(HttpServletResponse response,SwanLog log){
		CallResult<String> result = new CallResult<String>();
		if(hb_user == null){
			result.setCode(400);
			result.setMsg("请重新登录");
			return  GsonUtil.toJson(response);
		}
		List<String> titleList = new ArrayList<>();

		titleList.add("记录时间");
		titleList.add("姓名");
		titleList.add("体温");
		titleList.add("手机号");
		titleList.add("单位名称");
		titleList.add("家庭住址");
		titleList.add("备注");

		List<String> columnList = new ArrayList<>();
		columnList.add("createDate");
		columnList.add("name");
		columnList.add("temperature");
		columnList.add("mobile");
		columnList.add("dept");
		columnList.add("address");
		columnList.add("note");

		List<Map<String,Object>> list = null;
		try {
			if (log.getSwanId() == null) {
				WXUser wxUser = new WXUser();
				wxUser.setPhone(hb_user.getName());
				List<WXUser> wxUsers = wxUserDao.findAll(wxUser);
				if (wxUsers != null && wxUsers.size() > 0) {
					Swan swan = new Swan();
					swan.setOpenId(wxUsers.get(0).getOpenid());
					List<Swan> swans = swanDaoService.getAll(swan);
					if (swans != null) {
						log.setSwanId(swans.get(0).getId_prikey());
					}
				}else {
                    ExcelUtil.exportExcelBigData(response, "员工打卡信息.xlsx", titleList, columnList, list);
                    return null;
                }
			}
			list = wxUserDao.findSwanLogInfoMapData(log);
			ExcelUtil.exportExcelBigData(response, "员工打卡信息.xlsx", titleList, columnList, list);

		} catch (Exception e) {
			e.printStackTrace();
		}
		result.setCode(0);
		result.setMessage("导出成功");
		return  GsonUtil.toJson(result);
	}


	@LoginNotRequired
	@RequestMapping("wxAddSwanLog")
	public String addSwanLog(@Validated SwanLog swanLog)  {
		logger.info("扫码后入参：{}",swanLog.toString());

		CallResult<Swan> result = null;
		try {
			String openid = (String) session.getAttribute("wxAppOpenid");
			if(!isEmpty(openid)){
				swanLog.setOpenId(openid);
			}
			swanLog.setCreateDate(new Date());
			Swan param = new Swan();
			result = new CallResult<>();
			String swanId = String.valueOf(swanLog.getSwanId());
			if(swanId.length() != 6){
				swanId = String.format("%06d", swanLog.getSwanId());
			}
			param.setQrCode(swanId);
			Swan swan = swanDaoService.getByField(param);
			if(swan != null){
				swanLog.setSwanId(swan.getId_prikey());
			}else{

				result.setCode(400);
				result.setMsg("SwanId参数有误");
				return gson.toJson(result);
			}
			CallResult<String> swanResult = swanService.addSwanLog(swanLog);
			result.setCode(swanResult.getCode());
			result.setMsg(swanResult.getMsg());
			if(swanResult.getData() != null){
				result.setData(GsonUtil.fromJson(swanResult.getData(),Swan.class));
			}
			WXUser wxUser = (WXUser) session.getAttribute("wxUser");
			if(wxUser != null && wxUser.getId_prikey() != null && swanLog.getDept()!= null && !"".equals(swanLog.getDept())){
				WXUser wxUserParam = new WXUser();
				wxUserParam.setId_prikey(wxUser.getId_prikey());
				wxUserParam.setDeptName(swanLog.getDept());
				wxUserDaoService.set(wxUserParam);
			}
		} catch (Exception e) {
			logger.info(e.getMessage(),e);
			e.printStackTrace();
			result.setCode(400);
			result.setMsg("添加异常");
		}

		return gson.toJson(result);
	}


	@LoginNotRequired
	@RequestMapping("getClockInInfo")
	public String getClockInInfo(WxAppClockInfo wxAppClockInfo,HttpSession session){
		CallResult<List<WxAppClockInfo>> result = new CallResult<>();

		String openid = (String) session.getAttribute("wxAppOpenid");
		if(isEmpty(openid)){
			result.setCode(400);
			result.setMsg("参数有误，请重新登录");
			return  GsonUtil.toJson(result);
		}
		try {
			wxAppClockInfo.setOpenid(openid);
			List<WxAppClockInfo> list =  wxUserDao.getClockInInfo(wxAppClockInfo);
			for(WxAppClockInfo item : list){
				StringBuilder sb = new StringBuilder();
				sb.append(DateUtil.dateFormatString(item.getClockInTime(),"yyyy-MM-dd HH:mm:ss"));
				if(Constant.qrCodetype_bus.equals(item.getType())){
					sb.append("  乘坐公交车");
					sb.append(item.getClockName());

				}else if(Constant.clockHealth.equals(item.getType())){
					sb.append("  健康打卡");
					if(item.getTemperature() != null && !"".equals(item.getTemperature()) && !"null".equals(item.getTemperature())){
						sb.append(" 体温 ");
						sb.append(item.getTemperature());
					}

				}else {
					sb.append("  在");
					sb.append(item.getClockName());
					sb.append(" 扫码 ");
					if(item.getTemperature() != null && !"".equals(item.getTemperature()) && !"null".equals(item.getTemperature())){
						sb.append(" 体温 ");
						sb.append(item.getTemperature());
					}
				}
				item.setClockInStr(sb.toString());
			}
			result.setCode(0);
			result.setMsg("查询成功");
			result.setData(list);
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(400);
			result.setMsg("查询异常");
		}
		return GsonUtil.toJson(result);
	}


	@LoginNotRequired
	@RequestMapping("getWxField")
	public String getWxField(){

		CallResult<WxField> result = new CallResult<>();
		WxField wxField = new WxField();
		wxField.setField1("登记好自已的轨迹");
		wxField.setField2("预警确诊人员交集");
		wxField.setField3("个人防护更重要");
		result.setCode(0);
		result.setMsg("查询成功");
		result.setData(wxField);
		return  GsonUtil.toJson(result);
	}


	@LoginNotRequired
	@RequestMapping("addSwanAndMadeQrCode")
	public String addSwanAndMadeQrCode(String name){
		CallResult<String> result = new CallResult<>();
		try {
			result = wechatAppletService.addSwanAndQrCode(name);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return GsonUtil.toJson(result);
	}


	@LoginNotRequired
	@RequestMapping("addSwanAndMadeQrCodeBatch")
	public void addSwanAndMadeQrCodeBatch(){
		try {
			BusInfo param = new BusInfo();
			List<BusInfo> list = busInfoDaoService.getAll(null);
			String path =  ResourceUtils.getURL("classpath:").getPath()+"static/img/";
			System.out.println(path);
			for(BusInfo b : list){
				String qrName = "";
				CallResult<String>  result = wechatAppletService.addSwanAndQrCode(b.getBusName());
				if(result.isExec()){
					qrName = result.getData();
					imageUtil.signatureSynthesis(path+"model.jpg",path+"gg_"+qrName+".jpg",path + b.getBusType() + "/"+ b.getBusName() + ".jpg",2340,520,950,1020,b.getBusName());

					File file = new File(path + b.getBusType() + "/"+ b.getBusName() + ".jpg");
					imageUtil.handleDpi(file, 300, 300);

					BusInfo busInfo = new BusInfo();
					busInfo.setId_prikey(b.getId_prikey());
					busInfo.setFlag("1");
					busInfoDaoService.set(busInfo);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}
